package com.atguigu.edu.realtime.app.dim;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.beans.TableProcess;

import com.atguigu.edu.realtime.func.DimSinkFunction;
import com.atguigu.edu.realtime.func.TableProcessFunction;
import com.atguigu.edu.realtime.utils.MyKafkaUtil;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import com.ververica.cdc.connectors.mysql.table.StartupOptions;
import com.ververica.cdc.debezium.JsonDebeziumDeserializationSchema;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

/**
 * @Classname DimApp
 * @Date 2022/11/17 23:35
 * @Created by arun
 */
public class DimApp {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);

        /*env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        // 2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        // 2.3 job取消后，检查点是否保存
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        // 2.4 两个检查点之间的最小时间间隔
        // 0秒时开始备份检查点，但数据很多到了第6秒才完成，那第5秒的时候还要备份检查点吗？不要，第8秒后再开始
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        // 2.5 设置重启策略
        // 一共3次
        //env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 3000L));
        // 每30天有3次
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30), Time.seconds(3)));
        // 2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        // 状态是存在TaskManager堆内存中的，检查点存在什么地方？有可能在内存里面，也有可能在文件系统里，我们设置一下
        // 存在JobManager中
        //env.getCheckpointConfig().setCheckpointStorage(new JobManagerCheckpointStorage());
        // 存在文件系统中
        env.getCheckpointConfig().setCheckpointStorage("hdfs://8.130.41.215:8020/edu/ck");
        // 2.7 指定操作Hadoop的用户
        System.setProperty("HADOOP_USER_NAME", "atguigu");*/

        String topic = "topic_db";
        String groupId = "dim_app_group";

        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getKafkaConsumer(topic, groupId);
        DataStreamSource<String> kafkaStrDS = env.addSource(kafkaConsumer);
        //kafkaStrDS.print(">>");
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.map(JSON::parseObject);
        jsonObjDS.print();


        //TODO 5.对数据进行简单的ETL  清晰规则：如果data不是一个标准的json，属于脏数据，过滤掉
        SingleOutputStreamOperator<JSONObject> filterDS = jsonObjDS.filter(
                new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        try {
                            //如果在转换的过程中没有发生异常，说明是标准的json，继续向下游传递
                            jsonObj.getJSONObject("data");
                            if (jsonObj.getString("type").equals("bootstrap-start")
                                    || jsonObj.getString("type").equals("bootstrap-complete")) {
                                return false;
                            }
                            return true;
                        } catch (Exception e) {
                            //如果在转换的过程中发生了异常，说明不是标准的json，直接将其过滤掉
                            return false;
                        }
                    }
                }
        );
        //TODO 6.使用FlinkCDC读取配置表中数据---配置流
        MySqlSource<String> mySqlSource = MySqlSource.<String>builder()
                .hostname("hadoop101")
                .port(3306)
                .databaseList("edu_config")
                .tableList("edu_config.table_process")
                .username("root")
                .password("000000")
                .deserializer(new JsonDebeziumDeserializationSchema())
                .startupOptions(StartupOptions.initial())
                .build();

        DataStreamSource<String> mySqlDS = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "MySQL Source");
        // mySqlDS.print();

        //TODO 7.将配置流进行广播 并定义广播状态
        MapStateDescriptor<String, TableProcess> mapStateDescriptor
                = new MapStateDescriptor<String, TableProcess>("mapStateDescriptor",String.class,TableProcess.class);
        BroadcastStream<String> broadcastDS = mySqlDS.broadcast(mapStateDescriptor);

        //TODO 8.将业务流和广播流进行关联
        BroadcastConnectedStream<JSONObject, String> connectDS = filterDS.connect(broadcastDS);

        //TODO 9.对关联之后的数据进行处理  --- 判断是否为维度
        SingleOutputStreamOperator<JSONObject> dimDS = connectDS.process(
                new TableProcessFunction(mapStateDescriptor)
        );
        //TODO 10.将维度数据写到Phoenix中
        dimDS.print(">>>");
        dimDS.addSink(new DimSinkFunction());
        env.execute();

    }
}
